package com.xbongbong.saas.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.department.pojo.DepartmentUserPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author 吴峰
 * @date 2021/07/07 15:41
 */
public class UserFieldUtil {

    /**
     * 获取用户id信息，负责团队此处不进行拼接
     * @param explainList
     * @param paasFormDataEntity
     * @return
     * @throws XbbException
     */
    public static Set<String> getUserIdList(List<FieldAttrEntity> explainList,  PaasFormDataEntity paasFormDataEntity) throws XbbException {
        Set<String> userIdList = new HashSet<>();
        JSONObject data = paasFormDataEntity.getData();
        if (CollectionUtils.isEmpty(explainList) && Objects.isNull(data) && StringUtil.isEmpty(paasFormDataEntity.getOwnerId()) && StringUtil.isEmpty(paasFormDataEntity.getCreatorId())) {
            return userIdList;
        }
        Iterator<FieldAttrEntity> fieldAttrEntityIterator = explainList.iterator();
        while (fieldAttrEntityIterator.hasNext()) {
            FieldAttrEntity fieldAttrEntity = fieldAttrEntityIterator.next();
            String attr = fieldAttrEntity.getAttr();
            if ( Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.USER.getType()) ) {
                String userId = FastJsonHelper.getStringFromFormData(data, attr);
                if ( Objects.nonNull(userId) ) {
                    userIdList.add(userId);
                }
            } else if ( Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.CREATORID.getType()) ) {
                userIdList.add(paasFormDataEntity.getCreatorId());
            }else if ( Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.OWNERID.getType()) ) {
                userIdList.add(paasFormDataEntity.getOwnerId());
            } else if ( Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.USER_GROUP.getType()) ) {
                JSONArray jsonArrayUserGroup = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, attr, new JSONArray());
                jsonArrayUserGroup.forEach(str -> {
                    if ( Objects.nonNull(str) ) {
                        userIdList.add(str.toString());
                    }
                });
            } else if ( ExplainUtil.isSubForm(fieldAttrEntity.getFieldType())) {
                List<? extends FieldAttrEntity> fieldList = fieldAttrEntity.getSubForm().getItems();
                if ( Objects.isNull(fieldList) ) {
                    continue;
                }
                JSONArray subFormDataArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, attr, new JSONArray());
                for ( FieldAttrEntity subField : fieldList ) {
                    String subFieldAttr = subField.getAttr();
                    for ( Object subFormDataObject : subFormDataArr ) {
                        if (! (subFormDataObject instanceof Map)) {
                            continue;
                        }
                        JSONObject subFormData = (JSONObject) subFormDataObject;
                        if (FieldTypeEnum.USER_GROUP.getType().equals(subField.getFieldType())) {
                            JSONArray jsonArrayUserGroup = FastJsonHelper.getJsonArrOrDefaultFromFormData(subFormData, subFieldAttr, new JSONArray());
                            jsonArrayUserGroup.forEach(str -> {
                                if ( Objects.nonNull(str) ) {
                                    userIdList.add(str.toString());
                                }
                            });
                        } else if ( FieldTypeEnum.USER.getType().equals(subField.getFieldType())) {
                            String str = FastJsonHelper.getStringOrDefaultFromFormData(subFormData, subFieldAttr, "");
                            if ( StringUtil.isNotEmpty(str) ) {
                                userIdList.add(str);
                            }
                        }
                    }
                }
            }
        }
        return userIdList;
    }


    public static Set<String> getUserIdList(List<PaasFormDataEntityExt> dataList, List<FieldAttrEntity> explainList, List<Long> dataIdList) {
        Set<String> userIdList = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Set<String> userAttrSet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        explainList.forEach(fieldAttrEntity -> {
            Integer fieldType = fieldAttrEntity.getFieldType();
            if ( Objects.equals(fieldType,FieldTypeEnum.USER.getType()) || Objects.equals(fieldType,FieldTypeEnum.USER_GROUP.getType())
                    || Objects.equals(fieldType,FieldTypeEnum.CREATORID.getType()) || Objects.equals(fieldType,FieldTypeEnum.OWNERID.getType())
                    || Objects.equals(fieldType,FieldTypeEnum.COUSERID.getType())) {
                userAttrSet.add(fieldAttrEntity.getAttr());
            }
        });
        for(PaasFormDataEntityExt item: dataList) {
            dataIdList.add(item.getDataId());
            userIdList.addAll(getUserIdList(item, userAttrSet));
        }
        return userIdList;
    }

    public static Set<String> getUserIdList(PaasFormDataEntityExt paasFormDataEntityExt, Set<String> userAttrSet) {
        Set<String> userIdList = new HashSet<>();
        for ( String userAttr : userAttrSet ) {
            Object userIdObject = paasFormDataEntityExt.getData().get(userAttr);
            if ( Objects.isNull(userIdObject) ) {
                continue;
            }
            if ( userIdObject instanceof List ) {
                List<String> userIdArray = JSONArray.parseArray(JSON.toJSON(userIdObject).toString(), String.class);
                if ( CollectionsUtil.isNotEmpty(userIdArray) ) {
                    userIdList.addAll(userIdArray);
                }
            } else {
                userIdList.add(userIdObject.toString());
            }
        }
        userIdList.add(paasFormDataEntityExt.getCreatorId());
        userIdList.add(paasFormDataEntityExt.getOwnerId());
        return userIdList;
    }

    public static String getNameByUserList(List<UserEntity> userList) {
        if (CollectionUtils.isNotEmpty(userList)) {
            if (CollectionUtils.isNotEmpty(userList)) {
                List<String> nameList = new ArrayList<>();
                userList.forEach(item->{
                    nameList.add(item.getName());
                });
                return StringUtils.join(nameList, "、");
            }
        }
        return "";
    }

    public static Object getUserIdAndDeptIdList(Object value, String symbol) {
        if (value instanceof Map) {
            // 成员单选和部门单选
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(value));
            return jsonObject.get("id");
        } else if (value instanceof List) {
            List<DepartmentUserPojo> list = JSON.parseArray(JSON.toJSONString(value), DepartmentUserPojo.class);
            if (Objects.equals(ConditionEnum.EQUAL.getSymbol(), symbol)
                    || Objects.equals(ConditionEnum.NOEQUAL.getSymbol(), symbol)) {
                return list.get(0).getId();
            } else {
                List<Object> result = new ArrayList<>();
                list.forEach(item->{
                    result.add(item.getId());
                });
                return result;
            }

        }
        // 若放开了成员多选和部门多选，此处还要再做处理
        return value;
    }

    public static void getUserByDataInfo(JSONObject data, List<FieldAttrEntity> explainList, Set<String> userSet) {
        Map<String, List<? extends FieldAttrEntity>> subFormAttrMap = new HashMap<>();
        explainList.forEach(fieldAttrEntity -> {
            Integer fieldType = fieldAttrEntity.getFieldType();
            String attr = fieldAttrEntity.getAttr();
            if ( Objects.equals(fieldType,FieldTypeEnum.USER.getType()) || Objects.equals(fieldType,FieldTypeEnum.USER_GROUP.getType())
                    || Objects.equals(fieldType,FieldTypeEnum.CREATORID.getType()) || Objects.equals(fieldType,FieldTypeEnum.OWNERID.getType())
                    || Objects.equals(fieldType,FieldTypeEnum.COUSERID.getType())) {
                getUserIdsByDataInfo(data, attr, userSet);
            }else if (Objects.equals(FieldTypeEnum.SUB_FORM.getType(), fieldType)) {
                List<? extends FieldAttrEntity> items = fieldAttrEntity.getSubForm().getItems();
                List<FieldAttrEntity> finalItems = (List<FieldAttrEntity>) items;
                JSONArray subFormJsonArray = data.getJSONArray(attr);
                if (Objects.nonNull(subFormJsonArray) && subFormJsonArray.size() > BasicConstant.ZERO) {
                    subFormJsonArray.forEach(subFormJson -> {
                        getUserByDataInfo((JSONObject)subFormJson, finalItems, userSet);
                    });
                }
            }
        });
    }

    public static void getUserIdsByDataInfo(JSONObject data, String attr, Set<String> userSet) {
        Object userIdObject = data.get(attr);
        if (Objects.isNull(userIdObject)) {
            return;
        }
        if (userIdObject instanceof List) {
            userSet.addAll((List<String>)userIdObject);
        }else {
            userSet.add(userIdObject.toString());
        }
    }
}
